package com.beiding.workordersystem.system.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.beiding.workordersystem.common.helper.SessionHolder;
import com.beiding.workordersystem.common.service.BaseService;
import com.beiding.workordersystem.common.standard.E;
import com.beiding.workordersystem.system.dao.AccountDao;
import com.beiding.workordersystem.system.entity.AccountEntity;
import com.beiding.workordersystem.system.entity.RoleEntity;
import com.beiding.workordersystem.system.service.AccountService;
import com.beiding.workordersystem.system.service.ConfigPropertyService;
import com.beiding.workordersystem.system.service.RoleService;
import com.google.common.base.Joiner;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

import javax.validation.constraints.NotNull;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;

@Service
public class AccountServiceImpl extends BaseService implements AccountService, InitializingBean {

    @Autowired
    private AccountDao accountDao;

    @Autowired
    private RoleService roleService;

    @Autowired
    private PasswordEncoder passwordEncoder;

    @Autowired
    private ConfigPropertyService configPropertyService;

    @Autowired
    private SessionHolder sessionHolder;

    private String encodedDefaultPassword;

    public AccountEntity loadUserByUsername(String username) throws UsernameNotFoundException {
        AccountEntity userEntity = accountDao.selectOne(createQueryByAccount(username));
        if (userEntity == null) {
            return null;
        }
        List<RoleEntity> roleEntities = roleService.listByUserId(userEntity.getId());
        userEntity.setRoleEntities(new HashSet<>(roleEntities));
        return userEntity;
    }

    @Override
    public void changePassword(String oldPassword, String newPassword) {
        String name = SecurityContextHolder.getContext().getAuthentication().getName();
        AccountEntity accountEntity = accountDao.selectOne(createQueryByAccount(name));
        E.isTrue(accountEntity != null, "账户不存在");
        E.isTrue(passwordEncoder.matches(oldPassword, accountEntity.getPassword()), "原密码输入错误");
        setPassword(name, newPassword);
    }

    @Override
    public void setPassword(String username, @NotNull String password) {
        AccountEntity userEntity = accountDao.selectOne(createQueryByAccount(username));
        E.isTrue(userEntity != null, username + "用户不存在");
        userEntity.setPassword(passwordEncoder.encode(password));
        accountDao.updateById(userEntity);
    }

    @Override
    public void addAccount(AccountEntity accountEntity) {
        boolean exist = accountDao.exist(createQueryByAccount(accountEntity.getUsername()));
        E.isTrue(!exist, accountEntity.getUsername(), "已存在,无法添加");
        accountEntity.setId(createId());
        accountEntity.setPassword(encodedDefaultPassword);
        accountDao.insert(accountEntity);
    }

    @Override
    public void resetPassword(String[] ids) {
        List<String> fs = new ArrayList<>();
        for (String id : ids) {
            AccountEntity userEntity = accountDao.selectById(id);
            if (userEntity == null) {
                fs.add(id);
                continue;
            }
            userEntity.setPassword(encodedDefaultPassword);
            accountDao.updateById(userEntity);
        }
        if (fs.size() > 0) {
            E.error(Joiner.on(",").join(fs), "账号不存在无法重置密码");
        }
    }

    @Override
    public void deleteById(String accountId) {

        AccountEntity accountEntity = accountDao.selectById(accountId);

        if (accountEntity != null) {
            E.isTrue(!accountEntity.getUsername().equals(SecurityContextHolder.getContext().getAuthentication().getName()), "你不能删除自己");
            accountDao.deleteById(accountId);
            sessionHolder.forceOffline(accountEntity.getUsername());
        }
    }

    private LambdaQueryWrapper<AccountEntity> createQueryByAccount(String account) {
        return new QueryWrapper<AccountEntity>().lambda().eq(AccountEntity::getUsername, account);
    }

    @Override
    public void afterPropertiesSet() throws Exception {
        String defaultPassword = configPropertyService.getConfig("default_password");
        if (defaultPassword == null) {
            defaultPassword = "123456";
            configPropertyService.setConfig("default_password", defaultPassword, "默认用户密码");
        }

        //对默认密码进行编译
        this.encodedDefaultPassword = this.passwordEncoder.encode(defaultPassword);
    }

}
